<template>
  <div class="myself-page">
    <div class="avatar-div">
      <el-avatar :src="userAvatar" style="width: 80px; height: 80px"></el-avatar>
    </div>
    <div class="upload-div">
      <el-button @click="uploadPictureFn">上传图片</el-button>
    </div>
    <div class="line-div">
    </div>
    <div class="info-div">
      <div class="left-info-div">
        <div class="left-info-div-form">
          <el-form
              v-model="userInfo"
              ref="userInfoRef"
              :disabled="!canEditForm"
              label-width="100px"
              label-suffix=":">
            <el-form-item label="用户名" prop="username" class="info-item">
              <el-input v-model="userInfo.username" @blur="checkUsername"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex" class="info-item">
              <el-radio-group v-model="userInfo.sex">
                <template v-for="item in sexData">
                  <el-radio :label="item.value">{{item.label}}</el-radio>
                </template>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号" prop="phone" class="info-item">
              <el-input v-model="userInfo.phone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" class="info-item">
              <el-input v-model="userInfo.email" @blur="checkEmail"></el-input>
            </el-form-item>
            <el-form-item label="省份" prop="province" class="info-item">
              <el-select v-model="userInfo.province"
                         :clearable="true"
                         :filterable="true"
                         @blur="blurProvince"
                         @change="changeProvince"
              >
                <el-option v-for="item in provinceData" :value="item.value" :label="item.label" :key="item.key || item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="地市" prop="city" class="info-item">
              <el-select v-model="userInfo.city"
                         :clearable="true"
                         :filterable="true"
                         @blur="blurCity"
                         @change="changeCity"
              >
                <el-option v-for="item in cityData" :value="item.value" :label="item.label" :key="item.key || item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="区域" prop="area" class="info-item">
              <el-select v-model="userInfo.area"
                         :clearable="true"
                         :filterable="true"
              >
                <el-option v-for="item in areaData" :value="item.value" :label="item.label" :key="item.key || item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="详细地址" prop="address" class="info-item">
              <el-input v-model="userInfo.address" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="个人简介" prop="description" class="info-item">
              <el-input v-model="userInfo.description" type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="left-info-div-button">
          <el-button type="primary" @click="saveUserInfo" :loading="saveLoading">{{ canEditForm ? '保存' : '编辑' }}</el-button>
          <el-button type="primary" @click="updatePassword">修改密码</el-button>
        </div>
      </div>
      <div class="mid-info-div">

      </div>
      <div class="right-info-div">
        <h2>个人计划</h2>
      </div>
    </div>
  </div>

  <update-password-dialog
  :show-dialog="showUpdate"
  @update:showDialog="showUpdate = $event">
  </update-password-dialog>

  <upload-picture-dialog
      :show-dialog="uploadPictureItem.showDialog"
      :title="uploadPictureItem.title"
      @handle-close="uploadPictureClose($event)"
      @handle-closed="uploadPictureClosed($event)"
      @handle-confirm="uploadPictureConfirm($event)"
  >

  </upload-picture-dialog>
</template>

<script setup lang="ts">
import defaultAvatar from '@/assets/img/default-avatar.png';
import {getUserAvatar, getUserInfo, updateLocalUserInfo} from "@/utils/user-utils.ts";
import {onMounted, reactive, ref} from "vue";
import type {FormInstance} from "element-plus";
import {dictDataUtil} from "@/utils/common-request.ts";
import {SYSTEM_SEX} from "@/constants/dict-constants.ts";
import {checkIsNull, checkReg} from "@/utils/check-utils.ts";
import {elMessageTip, warningMessageTip} from "@/utils/tip-utils.ts";
import {email_reg} from "@/constants/format-constant.ts";
import {saveUserInfoReq} from "@/api/admin/user.ts";
import {RESPONSE_CODE_SUCCESS} from "@/config/common-config.ts";
import UpdatePasswordDialog from "@/components/myself/UpdatePasswordDialog.vue";
import {areaDataUtil} from "@/utils/common-request.ts";
import UploadPictureDialog from "@/components/myself/UploadPictureDialog.vue";

interface UserInfo {
  id: string;
  username: string;
  phone: string;
  email: string;
  sex: string
  province: string;
  city: string;
  area: string;
  address: string;
  description: string;
}

let userInfo = reactive<UserInfo>({
  id: '',
  username: '',
  phone: '',
  email: '',
  sex: '2',
  province: '',
  city: '',
  area: '',
  address: '',
  description: ''
})

const userInfoRef = ref<FormInstance>()

const userAvatar = ref<string>(getUserAvatar() || defaultAvatar);

const canEditForm = ref<boolean>(false);
const saveLoading = ref<boolean>(false);

const sexData = ref<any>(() => [])

const provinceData = ref<any>(() => [])

const cityData = ref<any>(() => [])

const areaData = ref<any>(() => [])

const initSexData = async () => {
  sexData.value = await dictDataUtil(SYSTEM_SEX);
}

const initProvinceInfo = async () => {
  provinceData.value = await areaDataUtil('0', '');
}

const initCityInfo = async (parentCode: string) => {
  cityData.value = await areaDataUtil(parentCode, '');
}

const initAreaInfo = async (parentCode: string) => {
  areaData.value = await areaDataUtil(parentCode, '');
}

const showUpdate = ref<boolean>(false);

const initUserInfo = () => {
  const localUserInfo = getUserInfo();
  userInfo.id = localUserInfo.userId
  userInfo.username = localUserInfo.username;
  userInfo.sex = localUserInfo.sex.toString();
  userInfo.phone = localUserInfo.phone;
  userInfo.email = localUserInfo.email;
  userInfo.province = localUserInfo.province
  userInfo.city = localUserInfo.city
  userInfo.area = localUserInfo.area
  userInfo.address = localUserInfo.address
  userInfo.description = localUserInfo.description
}

const saveUserInfo = async () => {

  if (!canEditForm.value) {
    canEditForm.value = !canEditForm.value;
    return;
  }
  saveLoading.value = true
  const checkResult = checkForm();

  if (checkResult) {
    const res: any = await saveUserInfoReq(userInfo);
    elMessageTip(res.tipType, res.message)
    saveLoading.value = false
    if (res.code === RESPONSE_CODE_SUCCESS){
      canEditForm.value = !canEditForm.value;
      await updateLocalUserInfo(userInfo.id)
    }
  }
}

const updatePassword = () => {
  showUpdate.value = true
}

const checkForm = ():boolean => {
  return checkUsername() && checkEmail();
}

const checkEmail = (): boolean => {
  const email = userInfo.email;
  if (checkIsNull(email)) {
    warningMessageTip("邮箱不能为空");
    return false;
  }

  if (!checkReg(email, email_reg)) {
    warningMessageTip("请注意邮箱格式");
    return false;
  }

  return true;
}

const checkUsername = (): boolean => {
  const username = userInfo.username;
  if (checkIsNull(username)) {
    warningMessageTip("用户名不能为空");
    return false;
  }

  return true;
}

const blurProvince = async () => {
  const currentProvince = userInfo.province;

  if (checkIsNull(currentProvince)) {
    userInfo.city = ''
    cityData.value = []
    userInfo.area = ''
    areaData.value = []
  } else {
    await initCityInfo(currentProvince)
  }
}

const blurCity = async () => {
  const currentCity = userInfo.city
  if (checkIsNull(currentCity)) {
    userInfo.area = ''
    areaData.value = []
  } else {
    await initAreaInfo(currentCity)
  }
}

const changeProvince = async (value: any) => {
  userInfo.city = ''
  cityData.value = []
  userInfo.area = ''
  areaData.value = []
  if (!checkIsNull(value)){
    await initCityInfo(value)
  }
}

const changeCity = async (value: any) => {
  userInfo.area = ''
  areaData.value = []
  if (!checkIsNull(value)){
    await initCityInfo(value)
  }
}

interface UploadPictureItem {
  showDialog: boolean;
  title: string;
}

const uploadPictureItem = reactive<UploadPictureItem>({
  showDialog: false,
  title: '上传图片'
})

const uploadPictureClose = (val: boolean) => {
  uploadPictureItem.showDialog = val;
}

const uploadPictureClosed = (val: boolean) => {
  uploadPictureItem.showDialog = val;
}

const uploadPictureConfirm = (val: any) => {
  userAvatar.value = val.filePath + '/' + val.finalFileName
  uploadPictureItem.showDialog = false;
}

const uploadPictureFn = () => {
  uploadPictureItem.showDialog = true;
}

onMounted(async () => {
  initSexData().then();
  initProvinceInfo().then()
  initUserInfo();
  blurProvince().then()
  blurCity().then()
})


</script>

<style scoped>
.myself-page {
  width: 100%;
  height: 100%;
}

.avatar-div {
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-div {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.line-div {
  width: 100%;
  height: 2px;
  background-color: #2e2e2b;
}

.info-div {
  width: 100%;
  height: calc(100% - 152px);
  display: flex;
}

.left-info-div {
  width: 600px;
  height: 100%;
}

.left-info-div-form {
  padding-top: 20px;
  width: 100%;
  height: 90%;
}

.left-info-div-button {
  width: 500px;
  height: 10%;
  text-align: center;
}

.mid-info-div {
  width: 2px;
  height: 100%;
  background-color: #2e2e2b;
}

.right-info-div {
  width: calc(100% - 602px);
  height: 100%;
}

.info-item {
  width: 500px;
}
</style>